package zsw.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class TestReflect {
	
	public static void main(String[] args) throws Exception, IllegalArgumentException, InvocationTargetException {
		Student s=new Student();
		s.setAge("23");
		s.setId(1);
		s.setName("zsw");
		Teacher t=new Teacher();
		List<Student> list=new ArrayList<Student>();
		list.add(s);
		t.setList(list);
		t.setTeacherId("110");
		t.setTeacherName("张光辉");
		
		//获取class的几种方式：通过对象getClass(),或者类的class，或者Class.forName("")
		
		
		
	
		
		
		//调用方法
		/*	Class<?> teacherClass = t.getClass();
		Teacher newInstance = (Teacher) teacherClass.newInstance();
		System.out.println(t==newInstance);
		Method[] methods = teacherClass.getDeclaredMethods();
		
		Method method = teacherClass.getMethod("says", String.class,Integer.class);
		method.invoke(t, "hah",23);
		
		Method method2 = teacherClass.getDeclaredMethod("says", null);
		method2.setAccessible(true);
		method2.invoke(t, args);
		
		//获取属性的值
		Field field = teacherClass.getDeclaredField("teacherName");
		field.setAccessible(true);
		Object object = field.get(t);
		System.out.println(object);
		//给属性赋值
		Field fieldR = teacherClass.getDeclaredField("r");
		fieldR.set(newInstance, "cdcd");
		Object objectR = fieldR.get(newInstance);
		System.out.println(objectR);*/
		
		
		
		
		
		//1.获取所有的方法
		/*for (int i = 0; i < methods.length; i++) {
			Method m=methods[i];
			System.out.println(m.getName());
			
			if("says".equals(m.getName())) {
				m.setAccessible(true);
				m.invoke(newInstance);
			}
			
		}
		Method[] method2 = teacherClass.getMethods();
		System.out.println("****************************");
		for (int i = 0; i < method2.length; i++) {
			Method m=method2[i];
			System.out.println(m.getName());
			if("say".equals(m.getName())) {
				m.invoke(newInstance);
			}
		}
		//2 获取所有的属性
		System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
		 Field[] fields = teacherClass.getFields();
		 Field[] declaredFields = teacherClass.getDeclaredFields();
		 for (int i = 0; i < fields.length; i++) {
			 Field field=fields[i];
			 System.out.println(field.getName());
		 }
		 System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&");
		for (int i = 0; i < declaredFields.length; i++) {
			 Field field=declaredFields[i];
			 System.out.println(field.getName());
			 if("teacherId".equals(field.getName())) {
				 field.setAccessible(true);
				 String object = (String) field.get(t);
				 System.out.println(object);
			 }
		}
		*/
		
		
		Class<?> teacherClass = Class.forName("zsw.reflect.Teacher");
		Constructor<?> constructor = teacherClass.getConstructor(String.class,Integer.class,String.class);
		Teacher newInstance = (Teacher) constructor.newInstance("A",34,"546");
		System.out.println(newInstance.getTeacherName());
	}

}
